import axios from 'axios'
import { ElMessage } from 'element-plus'
import encrypt from './encrypt.js'
import router from '@/router'

const request = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL + import.meta.env.VITE_APP_NAME,
    timeout: 10000000
})

// 不需要token验证的API白名单
const noTokenRequiredList = ['/api/pay/list-all-variants']

request.defaults.headers['Content-Type'] = 'application/json'
request.defaults.headers['Authorization'] = ''

request.interceptors.request.use(
    function (config) {
        // 判断当前请求是否在白名单中
        const isInWhiteList = noTokenRequiredList.some(api => {
            return config.url && config.url.includes(api)
        })

        // 不在白名单中的请求需要添加token
        if (!isInWhiteList) {
            config.headers['authorization'] = `Bearer ${encrypt.GetLocalData('accessToken')}` || ''
        }

        config.headers['ngrok-skip-browser-warning'] = '69420'
        return config
    },
    function (error) {
        return Promise.reject(error)
    }
)

// 添加响应拦截器
request.interceptors.response.use(function (res) {
    if (res.data.code == '10051') {
        ElMessage.error('登录过期')
        router.push('/login')
    } else if (res.data.code != 200) {
        ElMessage.error(res.data.msg || res.data.data)
    } else {
        let response = res.data
        return response
    }
})

export function post({ url, data, headers = {} }) {
    return new Promise((resolve, reject) => {
        request
            .post(url, data, { headers })
            .then(res => {
                if (res) {
                    resolve(res)
                } else {
                    reject(res)
                }
            })
            .catch(err => {
                reject(err)
            })
    })
}

export function get({ url, params = {} }) {
    return new Promise((resolve, reject) => {
        request
            .get(url, { params })
            .then(res => {
                if (res) {
                    resolve(res)
                } else {
                    reject(res)
                }
            })
            .catch(err => {
                reject(err)
            })
    })
}

export function put({ url, data }) {
    return new Promise((resolve, reject) => {
        request
            .put(url, data)
            .then(res => {
                if (res) {
                    resolve(res)
                } else {
                    reject(res)
                }
            })
            .catch(err => {
                reject(err)
            })
    })
}

export const serves = {
    get,
    post,
    put
}

export default request
